package com.leorui.schoollife

import com.leorui.schoollife.entity.PhotoEntity
import com.leorui.schoollife.filter.PhotoFilter
import com.leorui.schoollife.mapper.IDBIcons
import com.leorui.schoollife.mapper.IDBSchool
import com.leorui.schoollife.utils.EncryptUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.util.ResourceUtils
import java.io.File
import javax.annotation.PostConstruct

@Component
class Application {
    @Autowired(required = false)
    private var dbIcons: IDBIcons? = null

    @Autowired(required = false)
    private var dbSchool: IDBSchool? = null

    private val iconsPath = "icons"

    @PostConstruct
    fun init() {
        initStaticIcons()
        initSchool()
    }

    /**
     * 初始化static文件夹中的icons文件夹中的图片，头像图片
     */
    private fun initStaticIcons() {
        // 删除数据库记录所有图片
        // dbIcons?.deleteAllPhoto()
        // 重新文件夹获取
        val targetPath = getIconsPathFile()
        val photoFiles = targetPath.listFiles(PhotoFilter())
        val encrypt = EncryptUtils()
        photoFiles?.forEach {
            val fileMd5 = encrypt.convert2MD5(it)
            PhotoEntity(fileMd5).iconId?.let { iconId ->
                val result = dbIcons?.isPhotoAlive(iconId)
                if (result == 0) {
                    dbIcons?.addPhoto(iconId, iconsPath + "/" + it.name)
                }
            }
        }
    }

    private fun getIconsPathFile(): File {
        return ResourceUtils.getFile("src${File.separator}main${File.separator}resources${File.separator}static${File.separator}${iconsPath}")
    }

    private fun initSchool() {
        var flag = false
        dbSchool?.selectAllSchoolInfo()?.forEach {
            if (it?.schoolName?.equals("黑龙江大学") == true) {
                flag = true
            }
        }
        if (!flag) {
            dbSchool?.insertSchoolInfo("黑龙江大学", "http://xyw.hlju.edu.cn/", 1)
        }
    }
}